﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Delivery_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language="javascript" type="text/javascript">
    function uploadAndSubmit() {
        var form = document.forms["demoForm"];

        if (form["file"].files.length > 0) {
            // 寻找表单域中的 <input type="file" ... /> 标签
            var file = form["file"].files[0];
            // try sending 
            var reader = new FileReader();

            reader.onloadstart = function () {
                // 这个事件在读取开始时触发
                console.log("onloadstart");
                document.getElementById("bytesTotal").textContent = file.size;
            }
            reader.onprogress = function (p) {
                // 这个事件在读取进行中定时触发
                console.log("onprogress");
                document.getElementById("bytesRead").textContent = p.loaded;
            }

            reader.onload = function () {
                // 这个事件在读取成功结束后触发
                console.log("load complete");
            }

            reader.onloadend = function () {
                // 这个事件在读取结束后，无论成功或者失败都会触发
                if (reader.error) {
                    console.log(reader.error);
                } else {
                    document.getElementById("bytesRead").textContent = file.size;
                    // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
                    var xhr = new XMLHttpRequest();
                    xhr.open(/* method */"POST",
                    /* target url */"upload.jsp?fileName=" + file.name
                    /*, async, default to true */);
                    xhr.overrideMimeType("application/octet-stream");
                    xhr.sendAsBinary(reader.result);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4) {
                            if (xhr.status == 200) {
                                console.log("upload complete");
                                console.log("response: " + xhr.responseText);
                            }
                        }
                    }
                }
            }

            reader.readAsBinaryString(file);
        } else {
            alert("Please choose a file.");
        }
    } 
 </script>
</head>
<body> 
 <!-- 用于文件上传的表单元素 --> 
 <form name="demoForm" id="demoForm" method="post" enctype="multipart/form-data" 
 action="javascript: uploadAndSubmit();"> 
 <h1>File API Demo</h1> 
 <p> 
 </p> 
 <p>Upload File: <input type="file" name="files" /></p> 
 <p><input type="submit" value="Submit" /></p> 
 <div>Progessing (in Bytes): <span id="bytesRead"> 
 </span> / <span id="bytesTotal"></span> 
 </div> 
 </form> 
 </body>
</html>
